<template>
  <div class="container">

    <!-- <el-dialog v-model="data.dialogVisible"  class="dialog" :show-close="false" :close-on-click-modal="false"  width="100vw"  
      @closed="close">
      <template #title> -->
    <div class="my-header" v-loading="data.detail_loading">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="流程图" name="four" v-if="data.status == 1">
          <flowChart :processInstanceId="params.procInsId"></flowChart>
        </el-tab-pane>

        <el-tab-pane label="基本信息" name="first">
          <div v-if="data.dialogVisible">
            <Information ref="getAssociation" @valueFlag="valueFlag1" :addFlag="data.addFlag" @awardType="awardType"
              :orgAllList="data.orgAllList">
            </Information>
          </div>
        </el-tab-pane>
        <el-tab-pane label="附表信息" name="middle">
          <div v-if="data.awardSelect.sbjx == 1">
            <div v-if="data.awardSelect.sblx == 1">
              <Schedule ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.pants" :users="data.users"
                :addFlag="data.addFlag" @usersChange="usersChange" @paramsChange="paramsChange6"></Schedule>
            </div>
            <div v-else-if="data.awardSelect.sblx == 2">
              <fmzl ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.patents" :zlData="data.zlData"
                :addFlag="data.addFlag" @paramsChange="paramsChange22"></fmzl>
            </div>
            <div v-else-if="data.awardSelect.sblx == 3">
              <jsjrjzz ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.softwarecopyrights"
                :addFlag="data.addFlag" @paramsChange="paramsChange2"></jsjrjzz>
            </div>
            <div v-else-if="data.awardSelect.sblx == 4">
              <jsbz ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.technicalnorms"
                :addFlag="data.addFlag" @paramsChange="paramsChange1">
              </jsbz>
            </div>
            <div v-else-if="data.awardSelect.sblx == 5">
              <jsgf ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.technicalmethods"
                :addFlag="data.addFlag" @paramsChange="paramsChange">
              </jsgf>
            </div>
            <div v-else-if="data.awardSelect.sblx == 6">
              <xslz ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.composition"
                :addFlag="data.addFlag" @paramsChange="paramsChange5">
              </xslz>
            </div>
            <div v-else-if="data.awardSelect.sblx == 7">
              <xslw ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.thesis" :addFlag="data.addFlag"
                @paramsChange="paramsChange4"></xslw>
            </div>
          </div>
          <div v-else-if="data.awardSelect.sbjx == 2">
            <zdkjxmlxj ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.projects" :users="data.users"
              :addFlag="data.addFlag" @usersChange="usersChange" @paramsChange="paramsChange8">
            </zdkjxmlxj>
          </div>
          <div v-else>
            <cxptjsj ref="getMiddle" @valueFlag2="valueFlag2" :fbData="data.awardSelect.innovate" :users="data.users"
              :addFlag="data.addFlag" @usersChange="usersChange" @paramsChange="paramsChange9"></cxptjsj>
          </div>
        </el-tab-pane>
        <el-tab-pane label="附件信息" name="second">
          <platformFiles :files="data.fileList" @dataChange="dataChange" @filesParams="filesParams"></platformFiles>
        </el-tab-pane>
        <el-tab-pane label="变更记录" name="third" v-if="data.addFlag == 1">
          <record :changeLogs="data.changeLogs"></record>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-divider></el-divider>
    <div class="dialog-footer" style="float:left"  v-if="out ==0">
      <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm">
        <el-form-item label="审批意见" prop="comment">
              <el-input
                :rows="2"
                 type="textarea"
                  placeholder="审批意见"
                  v-model="ruleForm.comment"
                  style="width: 600px"
                  clearable
                />
            </el-form-item>
      </el-form>
    </div>

    <div class="dialog-footer" v-if="out ==0" style="float:right;">
      <el-button type="primary" @click="handlebh" style="margin-top:20px">驳回</el-button>
      <el-button type="primary" @click="handletg" style="margin-top:20px">通过</el-button>
    </div>
  </div>
</template>
<script lang="js">
import flowChart from '@/components/PublicProcess/Chart/flowChart.vue'

import * as proxy from "@/constants/proxy"
import request from "@/utils/request"
import Api from '@/views/science/api/awards'
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue'
import record from '@/views/science/components/record/record.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import cxptjsj from './cxptjsj.vue'
import fmzl from './fmzl.vue'
import Information from './information.vue'
import jsbz from './jsbz.vue'
import jsgf from './jsgf.vue'
import jsjrjzz from './jsjrjzz.vue'
import Schedule from './schedule.vue'
import xslw from './xslw.vue'
import xslz from './xslz.vue'
import zdkjxmlxj from './zdkjxmlxj.vue'

export default {

  props: {
    params: {
      type: Object,
      default: {},
    },
    out: {
      type: String,
      default: '0',
    }
  },
  components: {
    SelectOption,
    flowChart,
    Table,
    platformFiles,//附件
    Information,//基本信息
    Schedule,//科技奖项附表信息
    fmzl, //发明专利
    jsjrjzz, //计算机软件著作
    jsbz, //技术标准
    jsgf, //技术工法
    xslz, //学术论著
    xslw, //学术论文
    zdkjxmlxj, //重大科技项目立项奖
    cxptjsj, //创新平台建设奖
    record,//变更记录x
  },
  setup(props, { emit }) {


    const store = useStore()
    const startDate = ref(null);  // 开始时间绑定值
    const endDate = ref(null);  // 结束时间绑定值
    const activeName = ref('four')//tab切换
    const ruleForm = reactive({
      comment: '',
    })

    const rules = reactive({
      comment: [
        { required: true, message: '请输入审核意见', trigger: 'change', },
      ]
    })

    const ruleFormRef = ref()

    let data = reactive({
      orgAllList: [],
      times: null,
      taskId: '',
      businessKey: '',
      dealVisible: false,
      isLoading: false,
      detail_loading: false,
      constructionName: '',
      processInstanceId: '',
      changeLogs: [],//变更记录
      addFlag: 0,
      flag1: null,
      flag2: null,
      status: 1, //0编辑，1审核
      dialogVisible: true,//弹窗
      page: { page: 1, pageSize: 10, total: 0 },
      ids: [],
      time: [],
      searchParams: {
        projectName: '', // 项目名称
        applyClass: '',//申报类型
        awardApplyName: '', // 申报奖项
        startTime: '',
        endTime: '',
      },
      allTableData: [],
      columns: [
        {
          key: 'projectNo',
          width: 140,
          label: '项目编号',
        },
        {
          key: 'projectName',
          width: 140,
          label: '项目名称',
        },
        {
          key: 'applyClass',
          width: 140,
          label: '申报类型',
        },
        {
          key: 'awardApplyName',
          width: 140,
          label: '申报奖项',
        },
        {
          key: 'applyUnitName',
          width: 140,
          label: '申报单位',
        },
        {
          key: 'applyTime',
          width: 140,
          label: '申报时间',
        },
        {
          key: 'applyUser',
          width: 140,
          label: '申报人',
        },
        {
          key: 'status',
          width: 140,
          label: '状态',
          textColor: true
        },
      ],
      pants: [],
      users: [],
      fileList: [], //附件信息

      awardSelect: {
        sbjx: 1,
        sblx: 1,
        pants: {}, //附表信息-科技创新成果奖-科学奖项
        patents: {}, //附表信息-科技创新成果奖-发明专利
        softwarecopyrights: {}, //科技创新成果奖-软件著作权
        technicalnorms: {}, //科技创新成果奖-技术标准
        technicalmethods: {}, //科技创新成果奖-技术工法
        composition: {}, //科技创新成果奖-学术著作
        thesis: {}, //科技创新成果奖-学术论文
        projects: {}, //重大科技项目立项奖
        innovate: {}, //创新平台建设奖
      },
      zlData: {},
    })

    const loading = ref(true)//加载
    // 存储下拉框数组的对象
    const options = reactive({
      projectnameList: computed(() => store.state.technologyStrength.KJSL_DECLARATION_TYPE),
      unitnameList: computed(() => store.state.technologyStrength.KJSL_APPLYING_FOR_AWARDS1),
    })
    const changeValue = (item) => data.searchParams.applyClass = item.itemValue
    const changeValue1 = (item) => data.searchParams.awardApplyName = item.itemValue
    // 清除日期选择器,删除的时候将日期清空
    const dataPickerChange = () => {
      if (data.time) {
        data.searchParams.startTime = data.time[0];
        data.searchParams.endTime = data.time[1];
      } else {
        data.searchParams.startTime = null;
        data.searchParams.endTime = null;
        data.time = [];
      }
    };

    data.searchParams.page = data.page.page
    data.searchParams.pageSize = data.page.pageSize

    const getListData = () => { // 获取列表数据
      loading.value = true   // 加载
      data.isLoading = true
      Api.getTotalList(data.searchParams)
        .then((res) => { // 获取列表数据
          let resData = res.data.data // 获取列表数据
          resData.records.map((item) => {
            if (item.status == 0) {
              item.status = "待提交"
            } else if (item.status == 1) {
              item.status = "办理中"
            } else if (item.status == 2) {
              item.status = "正常办结"
            } else if (item.status == 3) {
              item.status = "已退回"
            }
            else if (item.status == 4) {
              item.status = "已撤办"
            }
            else if (item.status == 5) {
              item.status = "强制办结"
            }
            else if (item.status == 6) {
              item.status = "已废弃"
            }
            else if (item.status == 7) {
              item.status = "已挂起"
            }
            else if (item.status == 8) {
              item.status = "已驳回"
            }

            item.applyTime = new Date(item.applyTime).getFullYear() + `-` + (new Date(item.applyTime).getMonth() + 1) + `-` + new Date(item.applyTime).getDate()
          })
          data.allTableData = resData.records   // 获取列表数据
          data.page.total = resData.total   // 获取列表数据
          data.isLoading = false
        })
        .finally(() => { // 获取列表数据
          loading.value = false  // 获取列表数据
        }).catch((error) => {
          data.isLoading = false
        })
    }

    const closeVisable = () => {

      ruleFormRef.value.resetFields();
      data.dialogVisible = false



    }

    //详情数据获取
    const detailData = async (id) => {
      data.detail_loading = true
      data.dialogVisible = true

      Api.detailData({
        id: id
      })
        .then((res) => { // 获取列表数据
          const resData = res.data.data
          store.commit('technologyStrength/getachievementINFO', { ...resData.baseInfo })
          // store.commit('technologyStrength/getfbxxINFO', { ...resData.pants })
          data.users = res.data.data.users
          data.fileList = res.data.data.fileList
          data.changeLogs = res.data.data.changeLogs
          data.processInstanceId = resData.baseInfo.processInstanceId
          data.taskId = resData.baseInfo.currTaskTd
          data.softwarecopyrights = resData.softwarecopyrights
          data.awardSelect.pants = resData.pants
          //专利
          data.awardSelect.patents = resData.patents

          data.awardSelect.sbjx = resData.baseInfo.awardApplyId
          data.awardSelect.sblx = resData.baseInfo.applyClassId

          Object.assign(data.awardSelect, resData);
          // console.log('详情数据获取', data.awardSelect.projects);
          // data.addFlag = 1
          store.commit('technologyStrength/getAddFlag', 1)
          ruleForm.comment = ''
          data.addFlag = 1
          data.detail_loading = false
          // console.log('详情数据获取',resData);
        }).catch((error) => {
          data.detail_loading = false
        })
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      getListData()
    }

    // 删除
    const deleteList = () => {


      if (data.ids.length) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let list = []
          data.allTableData.forEach(e => {
            if (data.ids.includes(e.id)) {
              list.push(e.status)
            }
          })
          console.log('删除', list);
          if (list.includes('办理中') || list.includes('正常办结') || list.includes('已退回') || list.includes('已撤办') || list.includes('强制办结') || list.includes('已废弃') || list.includes('已挂起')) {
            tips('只允许删除待提交和已驳回状态的数据', 'warning')
          } else {
            // console.log('可以删除');
            let res = await Api.deleteList({
              id: data.ids + ''
            })
            if (res.data.success) {
              tips('删除成功', 'success')
              getListData()
            }
          }

        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }

    const valueFlag1 = (flag) => {
      data.flag1 = flag
    }
    const valueFlag2 = (flag) => {
      data.flag2 = flag
    }



    const awardType = (awardSelect) => {
      Object.assign(data.awardSelect, awardSelect)
      Object.assign(data.zlData, awardSelect)
      console.log('关联对象切换', awardSelect)
    }

    const paramsChange = (params) => {
      console.log(params)
      data.awardSelect.technicalmethods = params
    }

    const paramsChange1 = (params) => {
      console.log(params)
      data.awardSelect.technicalnorms = params
    }

    const paramsChange2 = (params) => {
      // console.log(params)
      data.awardSelect.softwarecopyrights = params
    }
    //专利
    const paramsChange22 = (params) => {
      // console.log(params)
      data.awardSelect.patents = params
    }

    const paramsChange4 = (params) => {
      console.log(params)
      data.awardSelect.thesis = params
    }

    const paramsChange5 = (params) => {
      console.log(params)
      data.awardSelect.composition = params
    }

    const paramsChange6 = (params) => {
      data.awardSelect.pants = params
    }

    const paramsChange8 = (params) => {
      data.awardSelect.projects = params
    }

    const paramsChange9 = (params) => {
      console.log(params)
      data.awardSelect.innovate = params
    }

    const delectIds = (ids) => {
      data.ids = ids
    }

    const currentChange = (current) => {
      data.searchParams.page = current
      getListData()
    }

    const dataChange = () => {//附件
      console.log(1)
    }

    const filesParams = (params) => {
      data.fileList = params
    }

    const usersChange = (params) => {
      data.users = params
    }

    //修改
    const handleEdit = (row) => {
      store.commit('technologyStrength/getRowId', row.id)
      detailData(row.id)
      data.status = 0
      activeName.value = 'first'
    }

    //提交
    const handletj = (row) => {
      Modals('是否提交本次内容', '提示', 'warning').then(async () => {
        let res = Api.startProcess({
          flowKey: 'tea1',
          businessKey: row.id,
          businessType: 'YW01',
          random: (new Date()).valueOf()
        })
        if (res) {
          data.dealVisible = true
          deal(row.id, 1)
        }

      }).catch(() => {
        console.log("点击了取消")
      })

    }

    //审核
    const handlesh = (row) => {
      activeName.value = 'four'
      store.commit('technologyStrength/getRowId', row.id)
      data.status = 1
      data.businessKey = row.id
      detailData(row.id)
    }

    //驳回
    const handlebh = () => {
      ruleFormRef.value.validate(valid => {
        if (valid) {


          Modals('是否通过本次内容', '提示', 'warning').then(async () => {
            let res = await Api.refuseProcess({
              procInsId: props.params.procInsId,
              comment: ruleForm.comment,
              businessKey: props.params.businessKey,
              businessType: 'YW01',
              random: (new Date()).valueOf()
            })
            if (res.data.code == 200) {
              tips('驳回成功', 'success')
            } else {
              tips(res.data.message, 'warning')

            }
          }).catch(() => {
            console.log("点击了取消")
          })
        }
      })
    }

    let deal = (id, state) => {
      data.times = setInterval(() => {
        Api.detailData({
          id: id
        })
          .then((res) => {
            const resData = res.data.data
            if (resData.baseInfo.status == state) {
              data.dealVisible = false
              getListData()
              clearTimeout(data.times)
            }
          })
      }, 1000);
    }

    //通过
    const handletg = () => {
      ruleFormRef.value.validate(valid => {
        if (valid) {

          Modals('是否通过本次内容', '提示', 'warning').then(async () => {
            let res = await Api.allowProcess({
              procInsId: props.params.procInsId,
              comment: ruleForm.comment,
              businessKey: props.params.businessKey,
              businessType: 'YW01',
              random: (new Date()).valueOf()
            })
            if (res.data.code == 200) {
              tips('审核成功', 'success')
            } else {
              tips(res.data.message, 'warning')

            }
          }).catch(() => {
            console.log("点击了取消")
          })
        }
      })
    }



    let dealCheck = (id) => {
      data.times = setInterval(() => {
        Api.detailData({
          id: id
        })
          .then((res) => {
            let resData = res.data.data
            if (resData.baseInfo.status == 2) {
              data.dealVisible = false
              getListData()
              clearTimeout(data.times)
            }

            if (resData.baseInfo.status == 1 && resData.baseInfo.currTaskTd !== data.taskId) {
              data.dealVisible = false
              ruleFormRef.value.resetFields();
              getListData()
              clearTimeout(data.times)
            }

          })

      }, 1000);
    }

    const getExport = () => {
      let msg = '是否导出全部数据'
      if (data.ids.length > 0) {
        msg = '是否导出所选数据'
      }
      Modals(msg, '提示', 'warning').then(async () => {
        const params = {
          ...data.searchParams,
          ids: data.ids
        }
        await Api.export(params, "科技成果奖励")
      }).catch(() => {
        console.log("点击了取消")
      })
    }



    //撤销
    const handlecx = (row) => {
      Modals('是否撤销审核通过的内容', '提示', 'warning').then(async () => {
        let res = await Api.rollback({
          id: row.id
        })
        if (res.data.success) {
          tips('撤销成功', 'success')
          getListData()
        }
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const add = () => {
      store.commit('technologyStrength/getAddFlag', 0)
      data.addFlag = 0
      data.dialogVisible = true //弹窗
      data.status = 0
      activeName.value = 'first'
      data.awardSelect.sbjx = 1
      data.awardSelect.sblx = 1
      store.commit('technologyStrength/emptyachievementINFO')
    }

    const close = () => {
      console.log('close');
      data.addFlag = 0
      data.dialogVisible = false
      data.fileList = []
      data.awardSelect.sbjx = 0
      data.awardSelect.sblx = 0
    }
    const getAssociation = ref()
    const getMiddle = ref()

    const getUnit = () => {

      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res => {
        data.orgAllList = res.data.data
      })
    }

    const sure = async () => { // 确定
      const form = store.state.technologyStrength.achievementINFO
      getAssociation.value.submitForm()
      getMiddle.value.submitForm()

      if (!data.flag1) {
        ElMessage({
          message: '请将基本信息补充完整',
          type: 'warning',
        })
        return
      }
      if (!data.flag2) {
        ElMessage({
          message: '请将附表信息补充完整',
          type: 'warning',
        })
        return
      }

      let params;
      if (data.awardSelect.sbjx == 1) {
        if (data.awardSelect.sblx == 1) {
          params = {
            baseInfo: form,
            pants: data.awardSelect.pants,
            users: data.users,
            fileList: data.fileList
          }
        } else if (data.awardSelect.sblx == 2) {
          params = {
            baseInfo: form,
            patents: data.awardSelect.patents,
            fileList: data.fileList
          }
        } else if (data.awardSelect.sblx == 3) {
          params = {
            baseInfo: form,
            softwarecopyrights: data.awardSelect.softwarecopyrights,
            fileList: data.fileList
          }
        } else if (data.awardSelect.sblx == 4) {
          params = {
            baseInfo: form,
            technicalnorms: data.awardSelect.technicalnorms,
            fileList: data.fileList
          }
        } else if (data.awardSelect.sblx == 5) {
          params = {
            baseInfo: form,
            technicalmethods: data.awardSelect.technicalmethods,
            fileList: data.fileList
          }
        } else if (data.awardSelect.sblx == 6) {
          params = {
            baseInfo: form,
            composition: data.awardSelect.composition,
            fileList: data.fileList
          }
        } else if (data.awardSelect.sblx == 7) {
          params = {
            baseInfo: form,
            thesis: data.awardSelect.thesis,
            fileList: data.fileList
          }
        }
      } else if (data.awardSelect.sbjx == 2) {
        params = {
          baseInfo: form,
          projects: data.awardSelect.projects,
          users: data.users,
          fileList: data.fileList
        }
      } else if (data.awardSelect.sbjx == 3) {
        params = {
          baseInfo: form,
          innovate: data.awardSelect.innovate,
          fileList: data.fileList
        }
      }
      let res
      if (form.id) {
        res = await Api.edit(params)
      } else {
        res = await Api.insert(params)
      }
      if (res.data) {
        tips('保存成功', 'success')
        store.commit('technologyStrength/emptyachievementINFO')
        getListData()  // 获取列表数据
        activeName.value = 'first'
        data.dialogVisible = false  // 弹窗
      }
    }

    
     getUnit()
    handlesh({ id: props.params.businessKey })

    return {
      dealCheck,
      delectIds,
      deal,
      changeValue,
      changeValue1,
      currentChange,
      search,
      filesParams,
      usersChange,

      valueFlag1,
      valueFlag2,
      awardType,
      paramsChange,
      paramsChange1,
      paramsChange2,
      paramsChange4,
      paramsChange5,
      paramsChange6,
      paramsChange8,
      paramsChange9,

      dataChange,
      getAssociation,
      activeName,
      options,
      data,
      ruleForm,
      rules,
      ruleFormRef,

      handleEdit,
      handletj,
      handlesh,
      handlecx,
      handlebh,
      handletg,
      closeVisable,
      // 列表
      getListData,
      // 新增
      add,
      sure,
      deleteList,
      startDate,
      endDate,
      getMiddle,
      dataPickerChange,
      getExport,
      close,
      paramsChange22,
    }
  },
}
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}

:global(.el-dialog__body) {
  padding: 0;
}

.el-col {
  line-height: 40px;
}

.el-form-item {
  .el-input {
    width: 100px;
    background-color: aliceblue;
  }

  .el-select {
    width: 100px;
  }
}

.custom-color {
  color: red !important;
  /* 确保优先级高于其他样式 */
}

.el-table th {
  background-color: #f0f0f0;
  /* 修改表头背景色 */
  color: #333;
  /* 修改表头文字颜色 */
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */

.open-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
}

/deep/.el-dialog {
  margin-top: none !important;
  position: absolute;
  height: 100vh;
  top: -15vh;
}


/deep/.el-dialog__body {
  display: block !important;
}

.mt15 {
  margin-top: 15px;
}

.dialog-footer {
  margin-top: 20px;
}

.mb10 {
  margin-bottom: 10px;
}

.tc {
  text-align: center;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
}


.el-dialog {
  padding: 0;
  width: 100vw;
}
</style>
